/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package facade;

import entity.Groups;
import entity.Role;
import entity.Users;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

/**
 *
 * @author shyfu_000
 */
@Stateless
public class UsersFacade extends AbstractFacade<Users> implements UsersFacadeLocal {

    @EJB
    private RoleFacadeLocal roleFacade;
    @PersistenceContext(unitName = "Delta-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UsersFacade() {
        super(Users.class);
    }

    /**
     *
     * @param range
     * @param status
     * @param sortBy
     * @return
     */
    @Override
    public List<Users> findRangeSortBy(int[] range, String sortBy) {
        return getEntityManager().createNamedQuery("Users.SortBy" + sortBy).setFirstResult(range[0]).setMaxResults(range[1] - range[0]).getResultList();
    }

    @Override
    public Collection<Groups> findGroupByUser(Integer idUser) {
        Users usr = find(idUser);
        Collection<Groups> grk = usr.getGroupsCollection();
        return grk;
    }
    
    @Override
    public Collection<Role> findRoleByUser(Integer idUser) {
        Users usr = find(idUser);
        Collection<Role> grk = usr.getRoleCollection();
        return grk;
    }

    @Override
    public List<Users> findRange(int offset, int noOfRecords) {

        return getEntityManager().createNamedQuery("Users.findAll").setFirstResult(offset).setMaxResults(noOfRecords).getResultList();

    }

    @Override
    public int count() {
        return Integer.parseInt(getEntityManager().createNamedQuery("Users.countRows").getSingleResult().toString());
    }

    public List<Users> findByKeyword(int offset, int noOfRecords, String keyword) {

        TypedQuery<Users> query = em.createNamedQuery("Users.findByKeyword", Users.class);

        query.setParameter("keyword", "%" + keyword + "%");
        query.setFirstResult(offset);
        query.setMaxResults(noOfRecords);
        List<Users> results = query.getResultList();
        return results;


    }

//    @Override
//    public int count(String status) { 
//        return Integer.parseInt(getEntityManager().createNamedQuery("Orders.countByStatus").setParameter("orderStatus",status).getSingleResult().toString());
//
//    }
    public boolean createUser(Users user, String[] roles) {
        boolean temp = false;
        String roleName = "";
        Users u = readByLogin(user.getLogin());
        if (u == null) {
            if (roles == null) {
                roleName = "Customer";
                createUserDefault(user, roleName);
            } else {
                if (roles.length >= 1) {
                    createUserWithRoles(user, roles);
                }
            }
        }
        return temp;
    }

    private void createUserWithRoles(Users user, String[] roles) {
        ArrayList<Role> listRole = new ArrayList<Role>();
        try {
            for (int i = 0; i < roles.length; i++) {
                Role role = roleFacade.readByName(roles[i]);
                listRole.add(role);
            }
            user.setRoleCollection(listRole);
            em.persist(user);
            for (int i = 0; i < roles.length; i++) {
                listRole.get(i).getUsersCollection().add(user);
                em.merge(listRole.get(i));
            }

        } catch (NoResultException e) {
            Logger.getLogger(UsersFacade.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    private void createUserDefault(Users user, String roleName) {
        try {
            Role role = roleFacade.readByName(roleName);
            Collection<Role> c = new ArrayList<Role>();
            c.add(role);
            user.setRoleCollection(c);
            role.getUsersCollection().add(user);
            em.persist(user);
            em.merge(role);
        } catch (NoResultException e) {
            Logger.getLogger(UsersFacade.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    @Override
    public Users readByLogin(String login) {
        Query query = em.createNamedQuery("Users.findByLogin");
        query.setParameter("login", login);
        Users user = null;
        try {
            user = (Users) query.getSingleResult();
        } catch (NoResultException ex) {
            return user;
        }
        return user;
    }
}
